package com.groupwork.resourcemonitoruserserver.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.groupwork.resourcemonitorcommon.common.ErrorCode;
import com.groupwork.resourcemonitorcommon.exception.BusinessException;
import com.groupwork.resourcemonitorcommon.utils.JWTToken;
import com.groupwork.resourcemonitormodel.domain.userServer.*;
import com.groupwork.resourcemonitoruserserver.mapper.*;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

//自定义realm
@Component
public class CustomerRealm extends AuthorizingRealm {

    @Resource
    private UserMapper userMapper;

    @Resource
    private PermissionMapper permissionMapper;

    @Resource
    private PermissionRoleRelationMapper permissionRoleRelationMapper;

    @Resource
    private UserRoleRelationMapper userRoleRelationMapper;

    @Resource
    private RoleMapper roleMapper;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权");
        //获取身份信息
        String primaryPrincipal = (String) principalCollection.getPrimaryPrincipal();
        //根据主身份信息获取角色 和 权限信息
        User aUser = userMapper.selectOne(new QueryWrapper<User>().eq("username", primaryPrincipal));
        System.out.println(primaryPrincipal);
        List<Role> roles = getUserRoles(aUser.getId());
        //遍历角色列表
        if (!CollectionUtils.isEmpty(roles)) {
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            roles.forEach(role -> {
                simpleAuthorizationInfo.addRole(role.getTitle());  //获取角色名称
                //权限信息
                List<Permission> perms = getRolePermissions(role.getId());
                if (!CollectionUtils.isEmpty(perms)) {
                    perms.forEach(viewPerms -> {
                        simpleAuthorizationInfo.addStringPermission(viewPerms.getTitle());
                    });
                }
            });
            System.out.println(simpleAuthorizationInfo);
            return simpleAuthorizationInfo;
        }
        return null;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("开始验证");
        //获取登入的身份信息
        String principal = (String) authenticationToken.getPrincipal();
        System.out.println(principal);
        //todo
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username",principal));
        if (!ObjectUtils.isEmpty(user)) {
            //ByteSource.Util.bytes(user.getSalt()) 通过这个工具将盐传入
            //如果身份认证验证成功，返回一个AuthenticationInfo实现；
            return new SimpleAuthenticationInfo(principal, user.getUsername(),getName());
        }else{
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }

    }

    //查询角色id
    public List<Role> getUserRoles(Long userId) {
        QueryWrapper<UserRoleRelation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        List<UserRoleRelation> userRoleList = userRoleRelationMapper.selectList(queryWrapper);
        List<Long> roleIds = userRoleList.stream().map(UserRoleRelation::getRoleId).collect(Collectors.toList());
        QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
        roleQueryWrapper.in("id", roleIds);
        try{
            return roleMapper.selectList(roleQueryWrapper);
        }catch (Exception exception){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

    }

    public List<Permission> getRolePermissions(Long roleId) {
        QueryWrapper<PermissionRoleRelation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id", roleId);
        List<PermissionRoleRelation> rolePermissionList = permissionRoleRelationMapper.selectList(queryWrapper);
        List<Long> permissionIds = rolePermissionList.stream().map(PermissionRoleRelation::getPermissionId).collect(Collectors.toList());
        QueryWrapper<Permission> permissionQueryWrapper = new QueryWrapper<>();
        permissionQueryWrapper.in("id", permissionIds);
        try{
            return permissionMapper.selectList(permissionQueryWrapper);
        }catch (Exception exception){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
    }

}